const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST']
  }
});

// 存储房间信息
const rooms = new Map();

// Socket.io连接处理
io.on('connection', (socket) => {
  console.log(`用户连接: ${socket.id}`);

  // 加入房间
  socket.on('join-room', (roomId) => {
    socket.join(roomId);
    
    // 更新房间用户信息
    if (!rooms.has(roomId)) {
      rooms.set(roomId, new Set());
    }
    rooms.get(roomId).add(socket.id);

    // 通知房间其他用户有新用户加入
    socket.to(roomId).emit('user-joined', socket.id);

    // 发送房间现有用户列表给新用户
    const users = Array.from(rooms.get(roomId));
    socket.emit('room-users', users.filter(id => id !== socket.id));

    console.log(`用户 ${socket.id} 加入房间 ${roomId}`);
  });

  // 处理offer
  socket.on('offer', ({ targetId, description }) => {
    io.to(targetId).emit('offer', {
      senderId: socket.id,
      description
    });
  });

  // 处理answer
  socket.on('answer', ({ targetId, description }) => {
    io.to(targetId).emit('answer', {
      senderId: socket.id,
      description
    });
  });

  // 处理ICE候选
  socket.on('ice-candidate', ({ targetId, candidate }) => {
    io.to(targetId).emit('ice-candidate', {
      senderId: socket.id,
      candidate
    });
  });

  // 处理断开连接
  socket.on('disconnect', () => {
    // 从所有房间中移除用户
    rooms.forEach((users, roomId) => {
      if (users.has(socket.id)) {
        users.delete(socket.id);
        // 如果房间空了，删除房间
        if (users.size === 0) {
          rooms.delete(roomId);
        } else {
          // 通知房间其他用户此用户已离开
          socket.to(roomId).emit('user-left', socket.id);
        }
      }
    });
    console.log(`用户断开连接: ${socket.id}`);
  });
});

// 静态文件服务
app.use(express.static('public'));

// 启动服务器
const PORT = process.env.PORT || 3002;
httpServer.listen(PORT, () => {
  console.log(`信令服务器运行在端口 ${PORT}`);
});